package com.dominator.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.typewrap.Dtos;
import com.dominFramework.core.utils.JsonUtils;
import com.dominFramework.core.utils.SystemUtils;
import com.dominator.enums.ReqEnums;
import com.dominator.mybatis.dao.*;
import com.dominator.repository.DaoQrLotteryTicket;
import com.dominator.repository.DaoUser;
import com.dominator.service.ApiUserService;
import com.dominator.service.ApiWzlService;
import com.dominator.utils.api.ApiMessage;
import com.dominator.utils.api.ApiMessageUtil;
import com.dominator.utils.api.ApiUtils;
import com.dominator.utils.encode.WzlEncryptUtil;
import com.dominator.utils.exception.ApiException;
import com.dominator.utils.network.HttpClientUtils;
import com.dominator.utils.system.PropertiesLoader;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApiWzlServiceImpl implements ApiWzlService {

    public static PropertiesLoader propertiesLoader = new PropertiesLoader("sysconfig.properties");

    @Autowired
    DaoUser daoUser;
    @Autowired
    T_merchantDao tMerchantDao;

    @Autowired
    DaoQrLotteryTicket qrLotteryTicketDao;
    @Autowired
    T_qr_lottery_ticketDao t_qr_lottery_ticketDao;




    @Override
    public ApiMessage getUnionId(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto,"merchantId,phoneNum");
        if (SystemUtils.isEmpty(daoUser.selectByPhoneNum(dto.getString("phoneNum")))){
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }
        //商户
        T_merchantPO tMerchantPO=tMerchantDao.selectByKey(dto.getString("merchantId"));
        if (SystemUtils.isEmpty(tMerchantPO)){
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }
        //联合登录
        System.out.println("加密前:"+dto.getString("phoneNum")+"_fenful_"+tMerchantPO.getMerchant_num());
        String enString1 = null;
        try {
            enString1 = WzlEncryptUtil.getInstance().encrypt(dto.getString("phoneNum")+"_fenful_"+tMerchantPO.getMerchant_num());
        } catch (Exception e) {
           throw new ApiException(ReqEnums.ENCODE_ERROR);
        }
        System.out.println("加密后的内容："+enString1);
        Dto resDto=Dtos.newDto();
        resDto.put("baseUrl",propertiesLoader.getProperty("union_login_url"));
        resDto.put("uniqueid",enString1);
        return ApiMessageUtil.success(resDto);

    }

    @Override
    public ApiMessage lotteryQrcodeQuery() throws ApiException {
        List<T_qr_lottery_ticketPO> usedTicketList = qrLotteryTicketDao.selectUsedTicket();
        String res=null;
        Dto resDto= Dtos.newDto();
        for (T_qr_lottery_ticketPO t_qr_lottery_ticketPO:usedTicketList){
            try {
                Thread.sleep(800);
                res=HttpClientUtils.get(propertiesLoader.getProperty("wzl_qrcode_query")+"?code="+t_qr_lottery_ticketPO.getQr_code());
            } catch (IOException e) {
                e.printStackTrace();
                throw new ApiException(ReqEnums.SYS_ERROR);
            } catch (InterruptedException e) {
                e.printStackTrace();
                throw new ApiException(ReqEnums.SYS_ERROR);
            }
            resDto= JsonUtils.toDto(res);
            if ("200".equals(resDto.getString("status"))){
                log.info("未消费二维码"+t_qr_lottery_ticketPO.getQr_code());
                t_qr_lottery_ticketPO.setUser_id(null);
                t_qr_lottery_ticketPO.setStatus("0");
                t_qr_lottery_ticketDao.updateByKey(t_qr_lottery_ticketPO);
                
            }else{
                log.info("已消费二维码"+t_qr_lottery_ticketPO.getQr_code());
                continue;
            }
        }
        return ApiMessageUtil.success();
    }

    @Override
    public ApiMessage lotteryQrcodeSend(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto,"merchantId,phoneNum");
        T_userPO userPO=daoUser.selectByPhoneNum(dto.getString("phoneNum"));
        if (SystemUtils.isEmpty(userPO)){
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }
        Dto resDto =Dtos.newDto();
        //黑名单客户不出票
        Boolean isBlack=ApiUtils.isMember("qrBlackList",dto.getString("phoneNum"));
        if (isBlack){
            log.info("黑名单用户:"+dto.getString("phoneNum")+"不出票");
            resDto.put("wzlQrcodeUrl", propertiesLoader.getProperty("wzl_qrcode_url"));
            return ApiMessageUtil.success(resDto);
        }

        Boolean isWhite=ApiUtils.isMember("qrWhiteList",dto.getString("phoneNum"));
        if (isWhite){
            String phoneNum=qrLotteryTicketDao.selectPartnerPhoneNum();
            userPO=daoUser.selectByPhoneNum(phoneNum);
            if (SystemUtils.isEmpty(userPO)){
                Dto dto1=Dtos.newDto();
                dto1.put("phoneNum",phoneNum);
                dto1.put("password","12345678");
                dto1.put("merchantId","e3ead303d51b4b41a8653209800dadb4");
                daoUser.createPhoneUser(dto1);
                userPO=daoUser.selectByPhoneNum(phoneNum);
            }
        }




        //查询余票
        Integer res=qrLotteryTicketDao.countTicketByMerchantId(dto);

        if(res<=0){
            throw new ApiException(ReqEnums.MERCHANT_OUT_OF_LIMIT);
        }
        //发放二维码
        T_qr_lottery_ticketPO t_qr_lottery_ticketPO=qrLotteryTicketDao.selectOneByMerchantId(dto);
        t_qr_lottery_ticketPO.setModify_time(new Date());
        t_qr_lottery_ticketPO.setUser_id(userPO.getId());
        t_qr_lottery_ticketPO.setStatus("1");
        t_qr_lottery_ticketDao.updateByKey(t_qr_lottery_ticketPO);

        resDto.put("wzlQrcodeUrl", propertiesLoader.getProperty("wzl_qrcode_url"));
        resDto.put("qrCode",t_qr_lottery_ticketPO.getQr_code());
        return ApiMessageUtil.success(resDto);
    }
}
